/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

package com.huawei.api.utils;

import com.huawei.api.bean.Language;
import com.huawei.api.exception.BaseCustomerException;
import com.huawei.api.exception.DataConvertException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * 文件工具类
 *
 * @since 2023/10/28
 */
public class FileUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 判断文件路径的文件是否存在
     *
     * @param fileName 文件名
     * @return boolean 是否存在
     */
    public static boolean fileIsExists(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return false;
        }
        File file = new File(fileName);
        return file.exists();
    }

    /**
     * 创建文件夹
     *
     * @param file 文件
     */
    public static void mkdir(File file) {
        try {
            FileUtils.forceMkdir(file);
        } catch (IOException exception) {
            LOGGER.debug("mkdir file failed.", exception);
        }
    }

    /**
     * 获取文件夹下的文件路径
     *
     * @param file 文件夹
     */
    public static void getFiles(File file, Collection<String> collection) {
        File[] files = file.listFiles();
        if (ObjectUtils.isEmpty(files)) {
            return;
        }
        for (File childrenFile : files) {
            if (childrenFile.isFile()) {
                collection.add(childrenFile.getAbsolutePath());
            } else if (childrenFile.isDirectory()) {
                getFiles(childrenFile, collection);
            }
        }
    }

    /**
     * 获取文件的后缀名称
     *
     * @param filePath 文件的绝对路径
     * @return 文件后缀
     */
    public static String getFileSuffix(String filePath) {
        String suffix = "";
        if (StringUtils.isNotBlank(filePath) && filePath.contains(".")) {
            suffix = filePath.substring(filePath.lastIndexOf(".") + 1);
        }
        return suffix;
    }

    /**
     * 根据语言获取文件路径列表
     *
     * @param language 语言类型
     * @param files 文件列表
     * @return 文件路径列表
     */
    public static List<String> getFileByLanguage(Language language, Set<String> files) {
        List<String> filePaths = new ArrayList<>();
        List<String> suffixes = language.getSuffixes();
        for (String file : files) {
            if (suffixes.contains(getFileSuffix(file))) {
                filePaths.add(file);
            }
        }
        return filePaths;
    }

    /**
     * 删除文件
     *
     * @param file 文件
     */
    public static void delFile(File file) {
        try {
            if (file.exists()) {
                FileUtils.forceDelete(file);
            }
        } catch (IOException e) {
            LOGGER.error("delete file failed.", e);
        }
    }

    /**
     * 获取资源文件的内容
     *
     * @param inputStream 资源文件流
     * @return String 内容
     */
    public static String getResourceFileContent(InputStream inputStream) throws BaseCustomerException {
        StringBuffer sb = new StringBuffer();
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException exception) {
            LOGGER.debug("read source file error, message is: {}", exception.getMessage());
            throw new BaseCustomerException("read resource file error");
        } finally {
            IOUtils.closeQuietly(bufferedReader);
            IOUtils.closeQuietly(inputStream);
        }
        return sb.toString();
    }

    public static String getFileContent(String filePath) throws BaseCustomerException {
        StringBuilder sb = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            LOGGER.info("fileUtil getFileContent filePath={}", StringConvertUtil.convert(filePath, "="));
            bufferedReader = Files.newBufferedReader(Paths.get(filePath), StandardCharsets.UTF_8);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException exception) {
            LOGGER.debug("read file error, message is: {}", exception.getMessage());
            throw new BaseCustomerException("read file error");
        } finally {
            IOUtils.closeQuietly(bufferedReader);
        }
        return sb.toString();
    }

    public static void writeStringToTxt(String content, String filePath) throws BaseCustomerException {
        try (BufferedWriter bufferedWriter = new BufferedWriter(
            new OutputStreamWriter(Files.newOutputStream(FileUtils.getFile(filePath).toPath()),
                StandardCharsets.UTF_8))) {
            bufferedWriter.write(content);
        } catch (IOException e) {
            LOGGER.error("write file error,message is: {}", e.getMessage());
            throw new DataConvertException("write file error");
        }
    }

    /**
     * 读取txt文件，保留换行符
     *
     * @param filePath filePath
     * @return
     * @throws BaseCustomerException
     */
    public static String readTxtToString(String filePath) throws BaseCustomerException {
        StringBuilder sb = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            LOGGER.info("fileUtil readStringToTxt filePath={}", StringConvertUtil.convert(filePath, "="));
            bufferedReader = Files.newBufferedReader(Paths.get(filePath), StandardCharsets.UTF_8);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException exception) {
            LOGGER.debug("read file error, message is: {}", exception.getMessage());
            throw new BaseCustomerException("read file error");
        } finally {
            IOUtils.closeQuietly(bufferedReader);
        }
        return sb.toString();
    }
}
